const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 班级弹窗
    show: false,
    loading: true,
    radio: '',
    className: "",
    // 搜索到的班级
    class: [],
    periods: "",
    // 创建课程
    course: {
      name: "",
      class: "",
      classId: null,
      Timedata: "",
      Members: []
    },
    // 判断是否绑定班级
    bindingClass: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let getopenid = App.cache.getOpenID()
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      getopenid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 打开弹窗
  showPopup() {
    wx.hideKeyboard()
    this.setData({
      show: true
    });

    this.getMyclass()
  },
  // 关闭弹窗
  onClosePopup() {
    this.setData({
      show: false
    });
  },
  // 单选框
  onChangeradio(event) {
    this.setData({
      radio: event.detail,
    });
  },
  // 单选框
  onClickradio(event) {
    let data = event.currentTarget.dataset;
    console.log('data', data);
    console.log('当前选中的班级的id：', data.value);
    console.log('当前选中的班级的名称：', data.name);
    if (!data.value) {
      this.setData({
        radio: "",
        className: "",
        ['course.class']: '',
        ['course.classId']: null,
        ['course.Members']: [],
        show: false,
        bindingClass: 0
      });
    } else {
      this.setData({
        radio: data.value,
        className: data.name,
        ['course.class']: data.name,
        ['course.classId']: data.value,
        ['course.Members']: data.list,
        show: false,
        bindingClass: 1
      });
    }
  },
  // 单选框 end



  // 获得input值
  handleChange(e) {
    console.log(e.detail.value);
    this.setData({
      ['course.name']: e.detail.value
    })
  },

  // 获得班级
  getMyclass() {
    db.collection('myclass').where(_.and([{
          Administrator: that.data.UserInfo.account
        },
        {
          classType: _.eq('课程班级')
        }
      ]))
      .get({
        success: function (res) {
          console.log(res.data)
          that.setData({
            class: res.data,
            loading: false,
          })
        }
      })
  },

  addcourse() {
    let bindingClass = that.data.bindingClass
    let course = that.data.course
    console.log('course', course);
    let courseId = (+new Date()).toString().substring(5, 13)
    if (bindingClass === 0) {
      // 没有绑定班级
      App.toast.showLoading('创建中')
      db.collection('course').add({
          data: {
            coursename: course.name,
            courseId: 'kc' + courseId,
            lecturer: {
              name: that.data.UserInfo.nickName,
              account: that.data.UserInfo.account,
              avatarUrl: that.data.UserInfo.avatarUrl,
              permissions: that.data.UserInfo.permissions,
            },
            class: {
              name: "",
                classId: null
            },
            courseMember: [that.data.UserInfo],
            Timedata: course.Timedata,
            courseTime: [],
            courseTimeTs: Date.now(),
            permissions: true
          }
        })
        .then(res => {
          //同时创建聊天社区
          db.collection('chat-msg').add({
            data: {
              coursename: course.name,
              courseId: 'kc' + courseId,
              className: "",
              classId: null,
              members: [that.data.UserInfo],
              records: [],
              ChatCommunityName: course.name,
              ChatCommunityId: 'chat' + 'kc' + courseId,
              Creator: {
                name: that.data.UserInfo.nickName,
                account: that.data.UserInfo.account
              },
              latestNewsTime: 0,
              chatType: "course",
              permissions: true,
              timeTs: Date.now(),
              calssAvatar: "https://6361-carlson-yun-6gsfgex5f4754200-1258487737.tcb.qcloud.la/calssAvatar/%E9%BB%98%E8%AE%A4/moren.png?sign=6b8b601d326a6a42b6d3ebe2a12613f5&t=1650470043"
            },
            success: function (res) {
              App.toast.hideLoading()
              console.log(res)
              App.toast.showToast('创建成功，即将返回')
              setTimeout(() => {
                App.route.relBack('/pages/course/list/index')
              }, 1500)
            }
          })
        })
        .catch(App.toast.hideLoading());
    } else {
      // 这是绑定班级的
      App.toast.showLoading('创建中')
      db.collection('course').add({
          data: {
            coursename: course.name,
            courseId: 'kc' + courseId,
            lecturer: {
              name: that.data.UserInfo.nickName,
              account: that.data.UserInfo.account,
              avatarUrl: that.data.UserInfo.avatarUrl,
              permissions: that.data.UserInfo.permissions,
            },
            class: {
              name: course.class,
                classId: course.classId
            },
            courseMember: course.Members,
            Timedata: course.Timedata,
            courseTime: [],
            courseTimeTs: Date.now(),
            termination: false,
            endTime: null,
            permissions: true,
          }
        })
        .then(res => {
          console.log(res)
          App.toast.hideLoading()
          App.toast.showToast('创建成功，即将返回')
          setTimeout(() => {
            App.route.relBack('/pages/course/list/index')
          }, 1500)
        })
        .catch(App.toast.hideLoading());
    }
  },
})